package com.glory;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

public class FileDown extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取服务器环境
        final ServletContext context = this.getServletContext();
        // 1.根据文件路径获取文件流
        final InputStream in = context.getResourceAsStream("/WEB-INF/classes/小程序4icon.png");
        // 2. 设置下载的文件名，中文文件名URLEncoder.encode编码，否则有可能乱码
        final String fileName = URLEncoder.encode("小程序4icon.png","UTF-8");
        // 3. 设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西
        resp.setHeader("Content-Disposition","attachment;filename="+fileName);
        // 4. 创建缓冲区
        int len = 0;
        final byte[] buffer = new byte[1024];
        // 5. 获取OutputStream对象
        final ServletOutputStream out = resp.getOutputStream();
        // 6. 将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端！
        while ((len = in.read(buffer)) > 0){
            out.write(buffer,0,len);
            System.out.println(len);
        }
        // 7.关闭流
        in.close();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
